<template>
  <PageContainer title="创建征文比赛">
    <div class="create-competition-container">
      <!-- 顶部操作栏：返回 + 发布 + 重置 -->
      <div class="top-operation">
        <el-button type="text" @click="handleBack">
          返回列表
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          发布比赛
        </el-button>
        <el-button type="text" @click="handleReset" style="margin-left: 16px">
          重置表单
        </el-button>
      </div>

      <!-- 征文比赛表单 -->
      <el-form
        :model="competitionForm"
        :rules="formRules"
        ref="competitionFormRef"
        label-width="120px"
        class="competition-form"
      >
        <!-- 比赛标题（必填唯一） -->
        <el-form-item label="比赛标题" prop="title">
          <el-input
            v-model="competitionForm.title"
            placeholder="请输入征文比赛标题（1-100字符，不可重复）"
            maxLength="100"
            show-word-limit
          />
        </el-form-item>

        <!-- 比赛主题（可选） -->
        <el-form-item label="比赛主题" prop="theme">
          <el-input
            v-model="competitionForm.theme"
            placeholder="请输入比赛核心主题（如：青春与成长）"
            maxLength="50"
            show-word-limit
          />
        </el-form-item>

        <!-- 比赛时间：下拉选择年/月/日（无日历弹窗） -->
        <el-form-item label="开始日期" prop="startDate">
          <div class="date-select-group">
            <!-- 选年 -->
            <el-select
              v-model="startYear"
              placeholder="年"
              style="width: 30%"
              @change="updateStartDays"
            >
              <el-option
                v-for="year in yearList"
                :key="year"
                :label="year + '年'"
                :value="year"
              />
            </el-select>
            <!-- 选月 -->
            <el-select
              v-model="startMonth"
              placeholder="月"
              style="width: 30%"
              @change="updateStartDays"
            >
              <el-option
                v-for="month in monthList"
                :key="month"
                :label="month + '月'"
                :value="month"
              />
            </el-select>
            <!-- 选日 -->
            <el-select
              v-model="startDay"
              placeholder="日"
              style="width: 30%"
            >
              <el-option
                v-for="day in startDayList"
                :key="day"
                :label="day + '日'"
                :value="day"
              />
            </el-select>
          </div>
        </el-form-item>

        <el-form-item label="结束日期" prop="endDate">
          <div class="date-select-group">
            <!-- 选年 -->
            <el-select
              v-model="endYear"
              placeholder="年"
              style="width: 30%"
              @change="updateEndDays"
            >
              <el-option
                v-for="year in yearList"
                :key="year"
                :label="year + '年'"
                :value="year"
              />
            </el-select>
            <!-- 选月 -->
            <el-select
              v-model="endMonth"
              placeholder="月"
              style="width: 30%"
              @change="updateEndDays"
            >
              <el-option
                v-for="month in monthList"
                :key="month"
                :label="month + '月'"
                :value="month"
              />
            </el-select>
            <!-- 选日 -->
            <el-select
              v-model="endDay"
              placeholder="日"
              style="width: 30%"
            >
              <el-option
                v-for="day in endDayList"
                :key="day"
                :label="day + '日'"
                :value="day"
              />
            </el-select>
          </div>
        </el-form-item>

        <!-- 比赛封面（可选） -->
        <el-form-item label="比赛封面" prop="cover">
          <el-upload
            class="avatar-uploader"
            action="/super/createCompetition"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="coverFileList"
            list-type="picture-card"
            :limit="1"
            name="cover"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">支持JPG、PNG格式，大小不超过2MB</div>
        </el-form-item>

        <!-- 举办平台（可选） -->
        <el-form-item label="举办平台" prop="platform">
          <el-input
            v-model="competitionForm.platform"
            placeholder="请输入举办平台（如：官网+APP）"
            maxLength="100"
            show-word-limit
          />
        </el-form-item>

        <!-- 奖项设置（可选） -->
        <el-form-item label="奖项设置" prop="awards">
          <el-input
            v-model="competitionForm.awards"
            type="textarea"
            :rows="4"
            placeholder="请输入奖项设置（如：一等奖1名：500元+证书）"
            maxLength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 比赛规则（可选） -->
        <el-form-item label="比赛规则" prop="rules">
          <el-input
            v-model="competitionForm.rules"
            type="textarea"
            :rows="6"
            placeholder="请输入比赛规则（如：字数限制、题材要求等）"
            maxLength="2000"
            show-word-limit
          />
        </el-form-item>

        <!-- 比赛描述（可选） -->
        <el-form-item label="比赛描述" prop="description">
          <el-input
            v-model="competitionForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入比赛简介（吸引用户参与）"
            maxLength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import PageContainer from '@/components/PageContainer.vue';
import { createCompetition } from '@/api/super';

const router = useRouter();
const competitionFormRef = ref(null);
const submitLoading = ref(false);
const coverFileList = ref([]);
const selectedFile = ref(null);

// ========== 年/月/日下拉选择器核心逻辑 ==========
// 1. 生成年份列表（近10年 + 后5年）
const currentYear = new Date().getFullYear();
const yearList = Array.from({ length: 15 }, (_, i) => currentYear - 10 + i);
// 2. 生成月份列表（1-12月）
const monthList = Array.from({ length: 12 }, (_, i) => i + 1);
// 3. 开始日期的年/月/日变量
const startYear = ref('');
const startMonth = ref('');
const startDay = ref('');
const startDayList = ref([]);
// 4. 结束日期的年/月/日变量
const endYear = ref('');
const endMonth = ref('');
const endDay = ref('');
const endDayList = ref([]);

// 计算当月天数（适配闰年2月）
const getDaysInMonth = (year, month) => {
  if (!year || !month) return [];
  return Array.from({ length: new Date(year, month, 0).getDate() }, (_, i) => i + 1);
};

// 监听开始日期的年/月变化，更新日列表
const updateStartDays = () => {
  startDayList.value = getDaysInMonth(startYear.value, startMonth.value);
  startDay.value = ''; // 重置日选择
};

// 监听结束日期的年/月变化，更新日列表
const updateEndDays = () => {
  endDayList.value = getDaysInMonth(endYear.value, endMonth.value);
  endDay.value = ''; // 重置日选择
};


// ========== 表单数据与校验 ==========
// 表单数据模型
const competitionForm = ref({
  title: '',
  theme: '',
  startDate: '', // 最终拼接成的日期：yyyy-MM-dd
  endDate: '',   // 最终拼接成的日期：yyyy-MM-dd
  cover: '',
  platform: '',
  awards: '',
  rules: '',
  description: ''
});

// 表单校验规则
const formRules = ref({
  title: [
    { required: true, message: '请输入比赛标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度需在1-100字符之间', trigger: 'blur' }
  ],
  theme: [
    { max: 50, message: '主题长度不可超过50字符', trigger: 'blur' }
  ],
  startDate: [
    { 
      validator: (rule, value, callback) => {
        // 校验开始日期的年/月/日是否都选择
        if (!startYear.value || !startMonth.value || !startDay.value) {
          callback(new Error('请选择完整的开始日期'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  endDate: [
    { 
      validator: (rule, value, callback) => {
        // 校验结束日期的年/月/日是否都选择
        if (!endYear.value || !endMonth.value || !endDay.value) {
          callback(new Error('请选择完整的结束日期'));
        } else {
          // 校验结束日期晚于开始日期
          const start = `${startYear.value}-${startMonth.value.toString().padStart(2, '0')}-${startDay.value.toString().padStart(2, '0')}`;
          const end = `${endYear.value}-${endMonth.value.toString().padStart(2, '0')}-${endDay.value.toString().padStart(2, '0')}`;
          if (dayjs(end).isBefore(dayjs(start))) {
            callback(new Error('结束日期需晚于开始日期'));
          } else {
            callback();
          }
        }
      },
      trigger: 'change'
    }
  ],
  platform: [
    { max: 100, message: '平台名称不可超过100字符', trigger: 'blur' }
  ],
  awards: [
    { max: 500, message: '奖项设置不可超过500字符', trigger: 'blur' }
  ],
  rules: [
    { max: 2000, message: '比赛规则不可超过2000字符', trigger: 'blur' }
  ],
  description: [
    { max: 1000, message: '比赛描述不可超过1000字符', trigger: 'blur' }
  ]
});


// ========== 封面上传与提交逻辑 ==========
// 封面文件选择回调
const handleFileChange = (file, fileList) => {
  selectedFile.value = file.raw;
  coverFileList.value = fileList;
};

// 提交表单：拼接年/月/日为日期字符串
const handleSubmit = async () => {
  try {
    // 1. 拼接开始/结束日期（格式：yyyy-MM-dd）
    competitionForm.value.startDate = `${startYear.value}-${startMonth.value.toString().padStart(2, '0')}-${startDay.value.toString().padStart(2, '0')}`;
    competitionForm.value.endDate = `${endYear.value}-${endMonth.value.toString().padStart(2, '0')}-${endDay.value.toString().padStart(2, '0')}`;

    // 2. 表单校验
    await competitionFormRef.value.validate();

    // 3. 开启加载状态
    submitLoading.value = true;

    // 4. 构造FormData
    const formData = new FormData();
    Object.entries(competitionForm.value).forEach(([key, value]) => {
      if (value) formData.append(key, value);
    });
    if (selectedFile.value) {
      formData.append('cover', selectedFile.value);
    }

    // 5. 调用创建接口
    const result = await createCompetition(formData);
    if (result.data.code === '0000') {
      ElMessage.success(result.data.msg || '征文比赛创建成功');
      router.push('/admin/super/competition');
    } else {
      ElMessage.error(result.data.msg || '征文比赛创建失败');
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error(error.message || '提交失败，请重试');
    }
    console.error('创建征文比赛异常：', error);
  } finally {
    submitLoading.value = false;
  }
};

// 重置表单
const handleReset = () => {
  competitionFormRef.value.resetFields();
  competitionForm.value = {
    title: '',
    theme: '',
    startDate: '',
    endDate: '',
    cover: '',
    platform: '',
    awards: '',
    rules: '',
    description: ''
  };
  // 重置日期选择
  startYear.value = '';
  startMonth.value = '';
  startDay.value = '';
  endYear.value = '';
  endMonth.value = '';
  endDay.value = '';
  coverFileList.value = [];
  selectedFile.value = null;
};

// 新增：返回列表方法
const handleBack = () => {
  router.push('/admin/super/competition'); // 请替换为实际的征文列表路由
};
</script>

<style lang="scss" scoped>
.create-competition-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.competition-form {
  max-width: 900px;
}

// 顶部操作栏样式
.top-operation {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
}

.submit-section {
  display: flex;
  align-items: center;
  margin-top: 30px;
}

/* 年/月/日下拉选择器布局 */
.date-select-group {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.avatar-uploader {
  margin-bottom: 10px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #409eff;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
  &:hover {
    border-color: #409eff;
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.el-textarea {
  resize: vertical;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>